package com.maxd.service.helpTask;


import com.alibaba.fastjson.JSONArray;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.*;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.helpTask.HelpTakeOrderRepository;
import com.maxd.respository.helpTask.HelpTaskJpaRepository;
import com.maxd.respository.helpTask.HelpTaskRepository;
import com.maxd.respository.timedTask.TimedTaskJpaRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.service.message.IMessageService;
import com.maxd.service.money.IMoneyDetailsService;
import com.maxd.service.userMoney.UserMoneyDetailsService;
import com.maxd.service.userMoney.UserMoneyService;
import com.maxd.service.userinfo.UserServiceImpl;
import com.maxd.utils.AmountCalUtils;
import com.maxd.utils.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 助力信息
 */
@Service
public class HelpTaskServiceImpl implements HelpTaskService {

    /** 助力信息jpa方法 */
    @Autowired
    private HelpTaskJpaRepository helpTaskJpaRepository;
    /** 平台抽成 */
    @Autowired
    private HelpRateService HelpRateService;
    /** 助力步骤详细信息 */
    @Autowired
    private HelpTaskDetailsService helpTaskDetailsService;
    /** 派单信息 */
    @Autowired
    private HelpTakeOrderService helpTakeOrderService;
    /** 助力信息自定义方法类 */
    @Autowired
    private HelpTaskRepository helpTaskRepository;
    /** 派单信息自定义方法类 */
    @Autowired
    private HelpTakeOrderRepository helpTakeOrderRepository;
    /** 定时任务 */
    @Autowired
    private TimedTaskJpaRepository timedTaskJpaRepository;
    /** 用户金额 */
    @Autowired
    private UserMoneyService UserMoneyService;
    /** 用户金额明细 */
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    /** 接单信息 */
    @Autowired
    private HelpSendOrderService helpSendOrderService;
    /** 维权信息 */
    @Autowired
    private HelpMaintainService helpMaintainService;
    /** 信誉分 */
    @Autowired
    private HelpUserScoreService helpUserScoreService;
    /** 信誉明细分 */
    @Autowired
    private HelpUserScoreDetailsService helpUserScoreDetailsService;
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserJpaRepository userJpaRepository;
    @Autowired
    private IMessageService iMessageService;
    @Autowired
    private UserServiceImpl userService;
    /** 用户钱包 */
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private IMoneyDetailsService moneyDetailsService;

    private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Double sumPrice(String time, Integer flag) {
        if(flag==1){
            return helpTaskRepository.sumPrice1(time);
        }else if(flag==2){
            return helpTaskRepository.sumPrice2(time);
        }else{
            return helpTaskRepository.sumPrice3(time);
        }
    }

    @Override
    public Double sumMoneyByProfit(String time, Integer flag) {
        if(flag==1){
            return helpTaskRepository.sumMoneyByProfit1(time);
        }else if(flag==2){
            return helpTaskRepository.sumMoneyByProfit2(time);
        }else{
            return helpTaskRepository.sumMoneyByProfit3(time);
        }
    }

    @Override
    public Integer countHelpTaskByCreateTime(String time, Integer flag) {
        if(flag==1){
            return helpTaskRepository.countHelpTaskByCreateTime1(time);
        }else if(flag==2){
            return helpTaskRepository.countHelpTaskByCreateTime2(time);
        }else{
            return helpTaskRepository.countHelpTaskByCreateTime3(time);
        }
    }

    @Override
    public HelpTask selectById(Long Id) {
        return helpTaskRepository.selectById(Id);
    }

    @Override
    public Result saveBody(HelpTask helpTask) {
        return ResultUtil.success(helpTask);
    }

    @Override
    @Transactional
    public int saveHelpTask(HelpTask helpTask, String helpTaskDetailss,Long userId ,Double money) {
        UserMoney userMoney=userMoneyService.selectByUserId(userId);
        String date=sdf.format(new Date());
        if(userMoney.getMoney()<money){
            //如果钱包金额不足，从账户可提现金额中扣
            UserInfo userInfo = userJpaRepository.findById(userId).orElse(null);
            Double moneys = 0.0;
            if("2".equals(userInfo.getIsSysUser())){
                moneys=AmountCalUtils.add(userMoney.getCannotMoney(),Double.parseDouble(userInfo.getJifen()));
            }else {
                moneys=AmountCalUtils.add(userMoney.getMoney(),Double.parseDouble(userInfo.getJifen()));
            }
            if(moneys<money){
                return 0;
            }else{
                Double money1 = 0.0;
                //从账户扣除费用
                if("2".equals(userInfo.getIsSysUser())){
                    UserMoneyService.updateCannotMoneyTwo(userId,Double.valueOf(money));
                    //userRepository.updateJiFenDelete(money1.toString(),userId);
                }else {
                    money1=AmountCalUtils.sub(money,userMoney.getMoney());
                    UserMoneyService.updateMoney(2,userId,userMoney.getMoney());
                    userRepository.updateJiFenDelete(money1.toString(),userId);
                }
                MoneyDetails userMoneyDetails=new MoneyDetails();
                userMoneyDetails.setUserId(userId);
                userMoneyDetails.setTitle("[派单扣款]派单ID："+helpTask.getId());
                userMoneyDetails.setContent("派单扣款："+userMoney.getMoney());
                userMoneyDetails.setType(2);
                userMoneyDetails.setMoney(userMoney.getMoney());
                userMoneyDetails.setCreateTime(date);
                if(userMoney.getMoney()>0.00){
                    moneyDetailsService.save(userMoneyDetails);
                }
                userMoneyDetails.setContent("派单费用扣费，不可提现金额不足，从可提现金额中扣除："+money1);
                userMoneyDetails.setMoney(money1);
                moneyDetailsService.save(userMoneyDetails);
            }
        }else{
            UserMoneyService.updateMoney(2,userId,money);
            MoneyDetails userMoneyDetails=new MoneyDetails();
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setTitle("[派单扣款]派单ID："+helpTask.getId());
            userMoneyDetails.setContent("派单扣款："+money);
            userMoneyDetails.setType(2);
            userMoneyDetails.setMoney(money);
            userMoneyDetails.setCreateTime(date);
            moneyDetailsService.save(userMoneyDetails);
        }

        List<HelpTaskDetails> helpTaskDetailsList= JSONArray.parseArray(helpTaskDetailss,HelpTaskDetails.class);
        helpTask.setState(0);
        CommonInfo three = commonRepository.findOne(56);
        if(three!=null && !three.getValue().equals("")){
            //计算平台扣除的费用
            Double price=AmountCalUtils.mul(Double.parseDouble(three.getValue()),helpTask.getTaskOriginalPrice());
            //原件减去扣除费用即每单价格
            Double prices=AmountCalUtils.sub(helpTask.getTaskOriginalPrice(),price);
            DecimalFormat formater = new DecimalFormat();
            formater.setMaximumFractionDigits(2);
            formater.setGroupingSize(0);
            formater.setRoundingMode(RoundingMode.FLOOR);
            helpTask.setTaskPrice(Double.parseDouble(formater.format(prices)));
        }else{
            helpTask.setTaskPrice(helpTask.getTaskOriginalPrice());
        }
        helpTask.setCreateTime(date);
        helpTask.setEndNum(0);
        helpTask=helpTaskJpaRepository.save(helpTask);
        for(HelpTaskDetails helpTaskDetails:helpTaskDetailsList){
            helpTaskDetails.setHelpTaskId(helpTask.getId());
        }
        helpTaskDetailsService.saveAll(helpTaskDetailsList);
        HelpTakeOrder helpTakeOrder=new HelpTakeOrder();
        helpTakeOrder.setUserId(userId);
        helpTakeOrder.setHelpTaskId(helpTask.getId());
        helpTakeOrder.setCreateTime(date);
        helpTakeOrder.setState(0);
        helpTakeOrderService.saveBody(helpTakeOrder);

        return 1;
    }


    @Override
    @Transactional
    public int updateHelpTask(String helpTakeId,Integer state,String content){
        if(state==3){
            state=2;
        }
        String[] split = helpTakeId.split(",");
        for (String s : split) {
            HelpTask helpTask=helpTaskRepository.selectById(Long.valueOf(s));
            if(helpTask.getState()==0){//只有待审核的可以审核
                HelpTakeOrder helpTakeOrder=helpTakeOrderService.selectHelpTakeOrderByHelpTaskId(helpTask.getId());
                UserInfo userByWxId = userRepository.getUserById(helpTakeOrder.getUserId());
                MessageInfo messageInfo = new MessageInfo();
                if(state==1){ //同意
                    //创建定时任务记录
                    TimedTask timedTask=new TimedTask();
                    timedTask.setType(1);
                    timedTask.setObjectId(helpTask.getId());
                    timedTask.setTitle("助力活动任务定时");
                    timedTask.setCreateTime(new Date());
                    try {
                        timedTask.setEndTime(sdf.parse(helpTask.getEndTime()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    timedTaskJpaRepository.save(timedTask);
                    messageInfo.setContent(userByWxId.getNickName() + " 您好！您的派单申请已经通过！");
                    if (userByWxId.getClientid() != null) {
                        userService.pushToSingle("派代申请", userByWxId.getNickName() + " 您好！您的派单申请已经通过！", userByWxId.getClientid());
                    }
                }else if(state==2){//拒绝则退还费用

                    Double money=AmountCalUtils.mul(helpTask.getTaskOriginalPrice(),helpTask.getTaskNum());
                    UserMoneyService.updateMoney(1,helpTakeOrder.getUserId(),money);
                    MoneyDetails userMoneyDetails=new MoneyDetails();
                    userMoneyDetails.setUserId(helpTakeOrder.getUserId());
                    userMoneyDetails.setTitle("[派单拒绝]派单ID："+helpTask.getId());
                    userMoneyDetails.setContent("派单退款："+money);
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setMoney(money);
                    userMoneyDetails.setCreateTime(sdf.format(new Date()));
                    moneyDetailsService.save(userMoneyDetails);
                    messageInfo.setContent(userByWxId.getNickName() + " 您好！您的派单申请被拒绝，金额自动退回，原因如下："+content+"！");
                    if (userByWxId.getClientid() != null) {
                        userService.pushToSingle("派代申请", userByWxId.getNickName() + " 您好！您的派单申请被拒绝，金额自动退回，原因如下："+content+"！", userByWxId.getClientid());
                    }
                }
                messageInfo.setState(String.valueOf(6));
                messageInfo.setTitle("派代申请");
                messageInfo.setUserName(userByWxId.getNickName());
                messageInfo.setUserId(String.valueOf(userByWxId.getId()));
                iMessageService.saveBody(messageInfo);

                //修改助力任务的状态
                helpTaskRepository.updateHelpTaskState(state,helpTakeOrder.getHelpTaskId());
                //修改派单的状态信息
                helpTakeOrderRepository.updateHelpTakeOrder(state,helpTakeOrder.getId(),content,helpTakeOrder.getCategory());
            }
        }
        return 1;
    }

    @Override
    public Page<Map<String,Object>> selectMyHelpTask(Integer state, Long userId, Pageable pageable){
        if(state==null||state==-1){
            return helpTaskRepository.selectMyHelpTask(userId,pageable);
        }
        return helpTaskRepository.selectMyHelpTask(userId,state,pageable);
    }

    @Override
    public Page<Map<String,Object>> selectParticipationHelpTask(Integer state,Long userId,Pageable pageable){
        if(state==null||state==-1){
            return helpTaskRepository.selectParticipationHelpTask(userId,pageable);
        }
        return helpTaskRepository.selectParticipationHelpTask(userId,state,pageable);
    }

    @Override
    public Page<HelpTask> selectHelpTaskList(Integer state,Pageable pageable){
        if(state==null||state==-1){
            return helpTaskRepository.selectHelpTaskList(pageable);
        }else{
            return helpTaskRepository.selectHelpTaskList(state,pageable);
        }

    }

    @Override
    public Page<HelpTask> selectHelpTaskLists(Integer state,String phone,Pageable pageable){
            return helpTaskRepository.selectHelpTaskLists(state,phone,pageable);
    }

    @Override
    public Page<Map<String,Object>> selectAuditHelpTask(Integer state,Long userId, Pageable pageable) {
        if(state==null||state==-1){
            return helpTaskRepository.selectAuditHelpTask(userId,pageable);
        }
        return helpTaskRepository.selectAuditHelpTask(state,userId,pageable);
    }


    @Transactional
    @Override
    public int finishHelpTask(HelpTask helpTask){
        //计算拒绝和放弃的数量
        Integer count=helpSendOrderService.selectEndNum(helpTask.getId());
        HelpTakeOrder helpTakeOrder=helpTakeOrderService.selectHelpTakeOrderByHelpTaskId(helpTask.getId());
        if(count==null){
            count=0;
        }
        //拒绝的数量加上剩余的数量
        count+=(helpTask.getTaskNum()-helpTask.getEndNum());
        if(count>0){
            Double money=AmountCalUtils.mul(count,helpTask.getTaskOriginalPrice());
            DecimalFormat formater = new DecimalFormat();
            formater.setMaximumFractionDigits(2);
            formater.setGroupingSize(0);
            formater.setRoundingMode(RoundingMode.FLOOR);
            money=Double.parseDouble(formater.format(money));
            UserMoneyService.updateMoney(1,helpTakeOrder.getUserId(),money);
            MoneyDetails userMoneyDetails=new MoneyDetails();
            userMoneyDetails.setUserId(helpTakeOrder.getUserId());
            userMoneyDetails.setTitle("派单结算，派单ID："+helpTask.getId());
            userMoneyDetails.setContent("派单结算："+money);
            userMoneyDetails.setType(1);
            userMoneyDetails.setMoney(money);
            userMoneyDetails.setCreateTime(sdf.format(new Date()));
            moneyDetailsService.save(userMoneyDetails);
        }
        //判断下是否有维权失败的记录 若有则不加信誉分
        Integer exits=helpMaintainService.selectCount(helpTask.getId(),1);
        if(exits==null || exits==0){
            helpUserScoreService.updateUserScore(helpTakeOrder.getUserId(),1,2);
            HelpUserScoreDetails helpUserScoreDetails=new HelpUserScoreDetails();
            helpUserScoreDetails.setUserId(helpTakeOrder.getUserId());
            helpUserScoreDetails.setTitle("[派单完成]任务Id："+helpTakeOrder.getHelpTaskId());
            helpUserScoreDetails.setContent("增加积分：2");
            helpUserScoreDetails.setCreateTime(sdf.format(new Date()));
            helpUserScoreDetails.setScore(2);
            helpUserScoreDetails.setType(1);
            helpUserScoreDetailsService.save(helpUserScoreDetails);
        }
        helpTaskRepository.updateHelpTaskState(4,helpTask.getId());
        helpTakeOrderRepository.updateHelpTakeOrder(3,helpTakeOrder.getId(),"结算完成",0);
        return 1;
    }

}
